#include "crcmgr.h"


uint16_t GetCrc(uint8_t *p, uint16_t Length)
{
  uint16_t crc=0xffff;
	uint8_t i;
	uint16_t gx=0x1021;
	while(Length--)
	{
		for(i=0x01;i!=0;i<<=1)
		{
			if((crc&0x8000)!=0)
			{
				crc<<=1;
				crc^=gx;
			}
			else
			{
				crc<<=1;
			}
			if(((*p)&i)!=0)
			{
				crc^=gx;
			}
		}
		p++;
	}
	return ~crc;
}

void SetResultCrc(uint8_t *p, char CmdType, char Result, char ErrType)
{
  uint16_t crc = 0;
  if(Result == 'f' || Result == 'F')
  {
    p[0] = 'F';
    p[1] = CmdType;
    p[2] = ErrType;
    crc = GetCrc(p, 3);
    p[3] = crc >> 8;
    p[4] = crc & 0x00ff;
  }
  else
  {
    p[0] = Result;
    crc = GetCrc(p, 1);
    p[1] = crc >> 8;
    p[2] = crc & 0x00ff;
  }
}